<?php
namespace App\Admin\Controller;

use App\Common\Controller\AbstractController;
use App\Server\Model\Webconfig;
use Hyperf\Di\Annotation\Inject;
use App\Admin\Validate\ConfValidate;
use Hyperf\Utils\Context;

class ConfController extends AbstractController
{
    /**
     * @Inject()
     * @var ConfValidate
     */
    protected $ConfValidate;


    public function oneIndex()
    {
        $page = $this->request->query('page');
        if ($page) {
            $param = $this->request->all();
            $webconfig = new Webconfig();
            $where = [];
            $where[] = ['type','=',2];
            if (!empty($param['config_key'])){
                $where[] = ['config_key','=',$param['config_key']];
            }
            $list = $webconfig->getListPage($where, ['*'], 'id desc', null,(int)$param['limit']);
            return $this->success($list['data'], '成功', ['count'=>$list['total']]);
        }
        else
        {
            return $this->render->render('/admin/conf/one_index');
        }
    }


    public function addOne()
    {
        $page = $this->request->query('page');
        if ($page) {
            $param = $this->request->all();
            unset($param['page']);
            $errorMessage = $this->ConfValidate->addOne($this->request);
            //验证部分数据合法性
            if ($errorMessage) {
                return $this->error('提交失败：' . $errorMessage);
            }
            $param['type'] = 2;
            $param['updated_at'] = date('Y-m-d H:i:s',time());
            $webconfig = new Webconfig();
            $addRes = $webconfig->dataAdd($param);
            $webconfig->clearCacheData();
            if ($addRes){
                return $this->success([],'创建成功');
            }else{
                return $this->error('创建失败');
            }
        }
        else
        {
            return $this->render->render('/admin/conf/add_one');
        }
    }

    public function editOne()
    {
        $id = $this->request->query('id');
        $webconfig = new Webconfig();
        $page = $this->request->query('page');
        if ($page) {
            $param = $this->request->all();
            unset($param['page']);
            $errorMessage = $this->ConfValidate->editOne($this->request);
            //验证部分数据合法性
            if ($errorMessage) {
                return $this->error('提交失败：' . $errorMessage);
            }
            $updateRes = $webconfig->dataUpdate([['id','=',$param['id']]],$param);
            $webconfig->clearCacheData();
            if ($updateRes){
                return $this->success([],'修改成功');
            }else{
                return $this->error('修改失败');
            }
        }
        else
        {
            $data = [];
            $data['data'] = $webconfig -> getInfo([['id','=',$id]],['*']);
            return $this->render->render('/admin/conf/edit_one', $data);
        }
    }


    public function deleteOne()
    {
        $id = $this->request->query('id');
        if(!$id) {
            return $this->error('缺少必要条件');
        }
        $webconfig = new Webconfig();
        $deleteRes = $webconfig->dataDelete([['id','=',$id]]);
        if (!$deleteRes) {
            return $this->error('删除失败！');
        }
        return $this->success([],'删除成功！');
    }


    public function index()
    {
        $Webconfig = new Webconfig();
        $data = [];
        // web配置
        $webconf = $Webconfig->getCacheInfo([['config_key','=','web']],'webconfig_web');
        $data['webConf'] = [
            'title'            => empty($webconf['title']) ? '' : $webconf['title'],
            'keywords'         => empty($webconf['keywords']) ? '' : $webconf['keywords'],
            'desc'             => empty($webconf['desc']) ? '' : $webconf['desc'],
            'logo'             => empty($webconf['logo']) ? '' : $webconf['logo'],
            'icp'              => empty($webconf['icp']) ? '' : $webconf['icp'],
            'code'             => empty($webconf['code']) ? '' : $webconf['code'],
        ];
        // email配置
        $emailconf = $Webconfig->getCacheInfo([['config_key','=','email']],'webconfig_email');
        $data['emailConf'] = [
            'smtp'     => empty($emailconf['smtp']) ? '' : $emailconf['smtp'],
            'username' => empty($emailconf['username']) ? '' : $emailconf['username'],
            'password' => empty($emailconf['password']) ? '' : $emailconf['password'],
            'port'     => empty($emailconf['port']) ? '' : $emailconf['port'],
            'email'    => empty($emailconf['email']) ? '' : $emailconf['email'],
            'from'     => empty($emailconf['from']) ? '' : $emailconf['from'],
        ];

        // 大鱼配置
        $dayuconf = $Webconfig->getCacheInfo([['config_key','=','sms']],'webconfig_sms');
        $data['dayuConf'] = [
            'appkey'     => empty($dayuconf['appkey']) ? '' : $dayuconf['appkey'],
            'secretkey' => empty($dayuconf['secretkey']) ? '' : $dayuconf['secretkey'],
            'FreeSignName' => empty($dayuconf['FreeSignName']) ? '' : $dayuconf['FreeSignName']
        ];

        return $this->render->render('/admin/conf/index',$data);
        
    }


    public function confSubmit()
    {
        $param = $this->request->all();

        switch ($param['type']) {
            case 'web':
                return $this->webConfSubmit($param);
                break;

            case 'email':
                return $this->emailConfSubmit($param);
                break;
            
            default:
                return $this->dayuConfSubmit($param);
                break;
        }
    }

    //提交网站信息
    private function webConfSubmit($param)
    {
        $adminInfo = Context::get('adminInfo');
        $errorMessage = $this->ConfValidate->index($this->request);
        //验证部分数据合法性
        if ($errorMessage) {
            return $this->error('提交失败：' . $errorMessage);
        }

        $post = $this->request->post();
        //验证  唯一规则： 表名，字段名，排除主键值，主键名
        $post['is_log'] = empty($post['is_log'])?0:$post['is_log'];
        $Webconfig = new Webconfig();
        $create = $Webconfig ->dataUpdateOrInsert(['config_key'=>'web'],['config_value'=>json_encode($post,JSON_UNESCAPED_UNICODE),'config_msg'=>'网站配置']);
        $Webconfig->getCacheInfo([['config_key','=','web']],'webconfig_web','update');
        if(false == $create) {
            return $this->error('提交失败');
        } else {
            addlog($this->request,$adminInfo['id'],'网站设置修改');
            return $this->success([],'提交成功');
        }
    }

    //提交邮箱配置
    private function emailConfSubmit($param)
    {
        $adminInfo = Context::get('adminInfo');
        $errorMessage = $this->ConfValidate->emailsetting($this->request);
        //验证部分数据合法性
        if ($errorMessage) {
            return $this->error('提交失败：' . $errorMessage);
        }

        $post = $this->request->post();
        //验证  唯一规则： 表名，字段名，排除主键值，主键名
        $post['is_log'] = empty($post['is_log'])?0:$post['is_log'];
        $Webconfig = new Webconfig();
        $create = $Webconfig ->dataUpdateOrInsert(['config_key'=>'email'],['config_value'=>json_encode($post,JSON_UNESCAPED_UNICODE),'config_msg'=>'网站发件邮箱配置']);
        $Webconfig->getCacheInfo([['config_key','=','email']],'webconfig_email','update');
        if(false == $create) {
            return $this->error('提交失败');
        } else {
            addlog($this->request,$adminInfo['id'],'网站发件邮箱设置修改');
            return $this->success([],'提交成功');
        }
    }

    //提交大鱼短信配置
    private function dayuConfSubmit($param)
    {
        $adminInfo = Context::get('adminInfo');
        $errorMessage = $this->ConfValidate->smssetting($this->request);
        //验证部分数据合法性
        if ($errorMessage) {
            return $this->error('提交失败：' . $errorMessage);
        }

        $post = $this->request->post();
        //验证  唯一规则： 表名，字段名，排除主键值，主键名
        $post['is_log'] = empty($post['is_log'])?0:$post['is_log'];
        $Webconfig = new Webconfig();
        $create = $Webconfig ->dataUpdateOrInsert(['config_key'=>'sms'],['config_value'=>json_encode($post,JSON_UNESCAPED_UNICODE),'config_msg'=>'网站短信发送配置']);
        $Webconfig->getCacheInfo([['config_key','=','sms']],'webconfig_sms','update');
        if(false == $create) {
            return $this->error('提交失败');
        } else {
            addlog($this->request,$adminInfo['id'],'网站短信设置修改');
            return $this->success([],'提交成功');
        }
    }
}
